package com.fyzk.base;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.ColorRes;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.bean.StringResultBean_New;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.SureDialog;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.fyzk.net.PublicMethod;
import com.fyzk.net.ToolsAesCrypt;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.Base64;
import com.fyzk.utils.GuideUtils;
import com.fyzk.utils.HandlerTypeUtils;
import com.fyzk.utils.L;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.utils.SystemStatusManager;
import com.gyf.immersionbar.ImmersionBar;
import com.tyjc.lottery.R;
import com.umeng.analytics.MobclickAgent;
import com.wf.domain.UrlDef;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;
import http.XRequestCallBack;

/**
 * 基础Activity
 */
public class BaseActivity extends AppCompatActivity implements
        OnClickListener, onTopTitleClickListener {

    protected final String TAG = this.getClass().getSimpleName();
    protected String url = UrlDef.TY_URL_NEW_DATA;
    public ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTranslucentStatus();
        super.onCreate(savedInstanceState);
        // 将当前activity放到activity管理器中
        ActivityTaskManager.getInstance().putActivity(
                getClass().getSimpleName(), this);
        x.view().inject(this);

        mImmersionBar = ImmersionBar
                .with(this)
                .statusBarColor(getStatusBarColor())
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)
                .autoDarkModeEnable(true)
                .addTag(TAG);
        mImmersionBar.init();
        initViews();
    }

    protected  @ColorRes int getStatusBarColor() {
        return R.color.top_bg1;
    }

    /**
     * 初始化数据
     */
    public void initViews() {

    }

    /**
     * 设置状态栏背景状态
     */
    protected void setTranslucentStatus() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            Window win = getWindow();
//            WindowManager.LayoutParams winParams = win.getAttributes();
//
//            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
//
//            winParams.flags |= bits;
//            win.setAttributes(winParams);
//        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            // 透明状态栏
//            getWindow().addFlags(
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            // 透明导航栏
//            getWindow().addFlags(
//                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            SystemStatusManager tintManager = new SystemStatusManager(this);
//            tintManager.setStatusBarTintEnabled(true);
//            // 设置状态栏的颜色
//            tintManager.setStatusBarTintResource(R.color.top_bg);
//            getWindow().getDecorView().setFitsSystemWindows(true);
//            ViewGroup contentFrameLayout = (ViewGroup) activity.findViewById(android.R.id.content);
//            View parentView = contentFrameLayout.getChildAt(0);
//            parentView.setFitsSystemWindows(true);
//        }

//        Window window = activity.getWindow();
//        View statusView = createStatusView(activity, R.color.toolbar_bg);
//        // 添加 statusView 到布局中
//        ViewGroup decorView = (ViewGroup) window.getDecorView();
//        decorView.setFitsSystemWindows(true);
//        decorView.addView(statusView);
//        // 设置根布局的参数
//        ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
//        rootView.setFitsSystemWindows(true);
//        rootView.setClipToPadding(true);
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(getResources().getColor(R.color.toolbar_bg));
//
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            // 设置状态栏透明
//
//            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//
//        }

    }

    /**
     * 生成一个和状态栏大小相同的矩形条
     *
     * @param activity 需要设置的activity
     * @param color    状态栏颜色值
     * @return 状态栏矩形条
     */
    private static View createStatusView(Activity activity, int color) {
        // 获得状态栏高度
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        int statusBarHeight = activity.getResources().getDimensionPixelSize(resourceId);

        // 绘制一个和状态栏一样高的矩形
        View statusView = new View(activity);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                statusBarHeight);
        statusView.setLayoutParams(params);
        statusView.setBackgroundColor(color);
        return statusView;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(getContext());
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(getContext());
        JPushInterface.onPause(this);
    }

    @Override
    protected void onStop() {
        // int version = Integer.valueOf(android.os.Build.VERSION.SDK);
        // if (version >= 5) {
        // overridePendingTransition(R.anim.activity_translate_in,
        // R.anim.activity_translate_out);
        // }
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (mImmersionBar != null)
//            mImmersionBar.destroy();
    }

    @Override
    public void finish() {
        callBackMap.clear();
        // 将当前activity从activity中移除
        ActivityTaskManager.getInstance().removeActivity(
                getClass().getSimpleName());
        super.finish();

    }

    protected void init() {
    }

    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            L.e(TAG, "handleMessage>>");
            parserMessage(msg);
        }
    };


    /**
     * post请求
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJson(int requestCode, String command, JSONObject params,
                             boolean showProgress) {
        sendRequestUseJson(requestCode, command, params, showProgress, this.url);
    }

    /**
     * post请求
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJson(int requestCode, String command, JSONObject params,
                             boolean showProgress, String url) {
        sendRequestUseJson(requestCode, command, params, showProgress, url);
    }

    /**
     * post请求(返回结果不加密)
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJsonNo(int requestCode, String command, JSONObject params,
                               boolean showProgress, String url) {
        sendRequestJson(requestCode, command, params, showProgress, url);
    }

    protected void onSuccess(int requestCode,
                             StringResultBean resultBean, String result) {

    }


    protected void onSuccess(int requestCode, StringResultBean_New resultBean, String
            result) {
    }

    protected void onSuccess(int requestCode, String result) {

    }

    protected void onFailure(int requestCode) {
        onFailure(requestCode, "");
    }

    protected void onFailure(int requestCode, String message) {
        onFailure(requestCode, "", message);
    }

    protected void onFailure(int requestCode, String errorCode, String message) {
        cancelProgressDialog();
        if (!TextUtils.isEmpty(message)) {
            AppToast.getToast().show(message);
        }
    }

    protected void onFailure(StringResultBean resultBean, int requestCode, String errorCode,
                             String message) {
        onFailure(requestCode, errorCode,
                message);
    }


    Map<String, XRequestCallBack<String>> callBackMap = new HashMap<>();

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param params2
     * @param showProgress
     */
    public void sendRequestUseJson(final int requestCode, String command,
                                   JSONObject params2, final boolean showProgress, String url) {
        if (!AppUtil.isNetworkAvailable(this)) {
            AppToast.getToast().show("网络错误!");
            BaseActivity.this.onFailure(requestCode, "网络错误!");
            return;
        }
        if (showProgress) {
            showProgressDialog();
        }
        XRequestCallBack<String> callBack = callBackMap.get(requestCode + "");
        if (callBack == null) {
            callBack = new XRequestCallBack<String>(requestCode) {
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    LogUtil.d("联网失败:" + ex.getMessage());
                    BaseActivity.this.onFailure(getRequestCode(), null);
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String netResult = null;
                    String decode_ = null;
                    LogUtil.d(requestCode+"联网返回成功:" + result);
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                    try {
                        decode_ = ToolsAesCrypt.Decrypt(result.replaceAll("\"",""),
                                UrlDef.stringFromJNI());
                        System.out.println("decode>" + decode_);
                        if(requestCode != CommandUtil.GETDIALOG){
                            byte[] base64d = Base64.decode(decode_);
                            byte[] decompress = PublicMethod.decompress2(base64d);
                            netResult = new String(decompress, "utf-8");
                        }else {
                            netResult = decode_;
                        }

                        LogUtil.d("联网：解密后返回>" + requestCode + ">" + netResult.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        StringResultBean resultBean = JSON.parseObject(netResult,
                                StringResultBean.class);
                        if (resultBean.getErrorcode().equals("0")) {
                            LogUtil.e("success>>>>>>");
                            BaseActivity.this.onSuccess(getRequestCode(), resultBean,
                                    netResult);
                        } else if (resultBean.getErrorcode().equals("110003")) {
                            MySharedPreferences.getInstance().setAuthToken("");
                            MySharedPreferences.getInstance().setLoginStatus(false);
                            BaseActivity.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        } else {
                            LogUtil.e("fail>>>>>>");
                            BaseActivity.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        LogUtil.d("BaseActivity >>  result 数据异常。。");
                        StringResultBean bean = null;
                        BaseActivity.this.onSuccess(getRequestCode(), bean,
                                netResult);
                    }
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                    this.onFinished();

                }
            };
            callBackMap.put(requestCode + "", callBack);
        }


        RequestParams params = new RequestParams(url);
        //打印请求
        try {
            JSONObject requstJson = new JSONObject();

            JSONObject clientInfo = new JSONObject();
            long timestamp = System.currentTimeMillis();
            if(requestCode != CommandUtil.GETDIALOG) {

                String token = http.DataUtil.md5.MD5.toMd5(http.DataUtil.md5.MD5.toMd5((UrlDef
                        .stringFromJNI() +
                        timestamp).getBytes()).getBytes());
                clientInfo.put("agentId", App.getChannel());
                clientInfo.put("apn", "WIFI");
                clientInfo.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
                clientInfo.put("model", "android");
                clientInfo.put("platform", "android");
                clientInfo.put("timestamp", timestamp);
                clientInfo.put("token", token);
                clientInfo.put("version", App.getVersionName());
                String branch = MySharedPreferences.getInstance().getBranch();
                String companyid = MySharedPreferences.getInstance().getCompanyid();
                if (TextUtil.isEmpty(branch)) {
                    branch = App.BRANCH;
                    MySharedPreferences.getInstance().setBranch(App.BRANCH);
                }
                if (TextUtil.isEmpty(companyid)) {
                    companyid = App.COMPANYID;
                    MySharedPreferences.getInstance().setCompanyid(App.COMPANYID);
                }
                clientInfo.put("branch", branch);
                clientInfo.put("companyid", companyid);
                requstJson.put("clientInfo", clientInfo);
                requstJson.put("command", command);
                if (params2 == null) params2 = new JSONObject();
                params2.put("sysCode", "HM");
                requstJson.put("data", params2);
                LogUtil.d("联网：加密前请求>" + requstJson.toString());
                String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
                LogUtil.d("联网：加密后请求>" + encrypt);
                params.setBodyContent("body=" + encrypt);
                RequestBody body = params.getRequestBody();
                body.setContentType("application/x-www-form-urlencoded");
                params.setRequestBody(body);
            }else {
                requstJson.put("command",command);
                LogUtil.d("联网：加密前请求>" + requstJson.toString());
                String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
                LogUtil.d("联网：加密后请求>" + encrypt);
                params.setBodyContent("body=" + encrypt);
                RequestBody body = params.getRequestBody();
                body.setContentType("application/x-www-form-urlencoded");
                params.setRequestBody(body);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("加密失败");
        }

        LogUtil.v("联网请求：" + params);
        x.http().post(params, callBack);

    }

    private ProgressDialog progressDialog;

    public void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("联网处理中……");
        }
        progressDialog.show();
    }

    protected void cancelProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
        }
    }

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params
     * @param showProgress
     */
    public void sendRequest(HttpMethod method, int requestCode, RequestParams params, final
    boolean showProgress) {


        if (!AppUtil.isNetworkAvailable(this)) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
            showProgressDialog();
        }

        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
//                onFailure(getRequestCode(), "网络异常");
                LogUtil.d("请求失败");
                if (showProgress) {
                    cancelProgressDialog();
                }
            }

            @Override
            public void onSuccess(String result) {
                LogUtil.d("联网返回成功：" + result);
                super.onSuccess(result);
                try {
                    StringResultBean resultBean = JSON.parseObject(result,
                            StringResultBean.class);
                    if (resultBean.getErrorcode().equals("0")) {
                        BaseActivity.this.onSuccess(getRequestCode(), resultBean,
                                result);
                    } else {
                        onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean
                                .getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    BaseActivity.this.onFailure(getRequestCode(), "9999",
                            "数据异常");
                }
                if (showProgress) {
                    cancelProgressDialog();
                }

            }
        };

        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.POST) {
            x.http().post(params, callBack);
        }
//        else if (method == HttpMethod.GET) {
//            x.http().get(params, callBack);
//        } else {
//            x.http().post(params, callBack);
//        }

    }


    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params
     * @param showProgress
     */
    public void sendRequestGet(HttpMethod method, int requestCode, RequestParams params,
                               final boolean showProgress) {

        if (!AppUtil.isNetworkAvailable(this)) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
            showProgressDialog();
        }

        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                LogUtil.d("请求失败");
                if (showProgress) {
                    cancelProgressDialog();
                }
            }

            @Override
            public void onSuccess(String result) {
                LogUtil.d("联网返回成功：" + result);
                super.onSuccess(result);
                BaseActivity.this.onSuccess(getRequestCode(), result);
                if (showProgress) {
                    cancelProgressDialog();
                }

            }
        };

        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }
    }

    /**
     * @param msg
     */
    protected void parserMessage(Message msg) {
        // cancelNetProgressDialog();
        if (msg == null)
            return;
        if (msg.what == HandlerTypeUtils.Re_LOGIN) {

            return;
        }
        switch (msg.what) {
            case HandlerTypeUtils.ZY_HANDLER_TYPE_ACCESS_ERROR:
                AppToast.getToast().show(R.string.text_neterror);
                break;
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_DATA:
                L.e(TAG, "ZY_HANDLER_TYPE_LOAD_DATA>>>>>>>>");
                // if (mLoadingView != null)
                // mLoadingView.loadOver();
                break;
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_DATA_FAIL:
                L.e(TAG, "ZY_HANDLER_TYPE_LOAD_DATA_FAIL>>>>>>>>");
                // if (mLoadingView != null)
                // mLoadingView.showError(msg.obj);
                break;
            case HandlerTypeUtils.ZY_HANDLER_TYPE_REFRESH:
                L.e(TAG, "ZY_HANDLER_TYPE_REFRESH>>>>>>>>");
                // if (mLoadingView != null)
                // mLoadingView.startLoad();
                break;
            case HandlerTypeUtils.ZY_HANDLER_FAIL_HTTP_EXCEPTION:
                L.e(TAG, "ZY_HANDLER_FAIL_HTTP_EXCEPTION>>>>>>>>");
                break;
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_DATA_EMPTY:
                L.e(TAG, "ZY_HANDLER_TYPE_LOAD_DATA_EMPTY>>>>>>>>");
                // if (mLoadingView != null) {
                // showEmpty();
                // }
                break;
            default:
                break;
        }
    }

    public Context getContext() {
        return this;
    }

    @Override
    public void onClick(View arg0) {

    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onCenterClick() {

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onRight2Click() {

    }

    public void showToast(String str) {
        AppToast.getToast().show(str);
    }

    public void showToast(int str) {
        AppToast.getToast().show(str);
    }

    /**
     * 数字彩倒计时
     *
     * @param lotteryId
     */
    protected void endTime(int lotteryId) {
        boolean isShowDialog = (!AppLotteryInfos.period_buffer.toString().contains(
                AppLotteryInfos.getPeriod(lotteryId) + lotteryId) && this.hasWindowFocus());


        if (lotteryId == LotteryIDUtils.SSQ_LOTTERY_ID_INT
                && AppLotteryInfos.Ssq_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.Ssq_Period, isShowDialog, lotteryId);
        }

        if (lotteryId == LotteryIDUtils.DLT_LOTTERY_ID_INT
                && AppLotteryInfos.Dlt_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.Dlt_Period, isShowDialog, lotteryId);
        }

        if (lotteryId == LotteryIDUtils.FC3D_LOTTERY_ID_INT
                && AppLotteryInfos.Fc3d_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.Fc3d_Period, isShowDialog, lotteryId);
        }

        if (lotteryId == LotteryIDUtils.PL3_LOTTERY_ID_INT
                && AppLotteryInfos.Pl3_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.Pl3_Period, isShowDialog, lotteryId);
        }

        if (lotteryId == LotteryIDUtils.PL5_LOTTERY_ID_INT
                && AppLotteryInfos.Pl5_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.Pl5_Period, isShowDialog, lotteryId);
        }

        if (lotteryId == LotteryIDUtils.QXC_LOTTERY_ID_INT
                && AppLotteryInfos.Qxc_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.Qxc_Period, isShowDialog, lotteryId);
        }

        if (lotteryId == LotteryIDUtils.QLC_LOTTERY_ID_INT
                && AppLotteryInfos.Qlc_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.Qlc_Period, isShowDialog, lotteryId);
        }


        // 高频彩种
        if (lotteryId == LotteryIDUtils.SD11XUAN5_LOTTERY_ID_INT
                && AppLotteryInfos.SD11xuan5_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.SD11xuan5_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.GD11XUAN5_LOTTERY_ID_INT
                && AppLotteryInfos.GD11xuan5_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.GD11xuan5_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.XJ11XUAN5_LOTTERY_ID_INT
                && AppLotteryInfos.XJ11xuan5_endTime <= 0) {
            showEndTimeDialog(AppLotteryInfos.XJ11xuan5_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.CQSSC_LOTTERY_ID_INT
                && AppLotteryInfos.GpSSC_endTime <= 0) {

            showEndTimeDialog(AppLotteryInfos.GpSSC_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.NXK3_LOTTERY_ID_INT
                && AppLotteryInfos.NXK3_endTime <= 0) {

            showEndTimeDialog(AppLotteryInfos.NXK3_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.ANHUIK3_LOTTERY_ID_INT
                && AppLotteryInfos.AnHuiK3_endTime <= 0) {

            showEndTimeDialog(AppLotteryInfos.AnHuiK3_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.JSK3_LOTTERY_ID_INT
                && AppLotteryInfos.JSK3_endTime <= 0) {

            showEndTimeDialog(AppLotteryInfos.JSK3_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.JLK3_LOTTERY_ID_INT
                && AppLotteryInfos.JLK3_endTime <= 0) {

            showEndTimeDialog(AppLotteryInfos.JLK3_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.KLSF_LOTTERY_ID_INT
                && AppLotteryInfos.KLSF_endTime <= 0) {

            showEndTimeDialog(AppLotteryInfos.KLSF_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.GDKLSF_LOTTERY_ID_INT
                && AppLotteryInfos.GDKLSF_endTime <= 0
        ) {

            showEndTimeDialog(AppLotteryInfos.GDKLSF_Period, isShowDialog, lotteryId);
        }
        if (lotteryId == LotteryIDUtils.GXK3_LOTTERY_ID_INT
                && AppLotteryInfos.GXK3_endTime <= 0) {

            showEndTimeDialog(AppLotteryInfos.GXK3_Period, isShowDialog, lotteryId);
        }

        if (lotteryId == LotteryIDUtils.KLPK_LOTTERY_ID_INT
                && AppLotteryInfos.KLPK_endTime <= 0) {

            showEndTimeDialog(AppLotteryInfos.KLPK_Period, isShowDialog, lotteryId);
        }
    }

    /**
     * 时间截止提示对话框
     */
    protected void showEndTimeDialog(String period, boolean isShowDialog, int lotteryId) {
        if (isShowDialog && period != null && !period.equals("")) {
            try {
                AppLotteryInfos.period_buffer.append(period + lotteryId);
                new SureDialog(this, new SureDialog.OnDialogOKCancleClickListener() {

                    @Override
                    public void onOKClick() {
                    }

                    @Override
                    public void onCancleClick() {
                    }
                }, "" + AppLotteryInfos.getLotteryName(lotteryId), "第" + period + "期已截止！", "确定",
                        "").show();
            } catch (Exception e) {
                L.e(TAG, e.getMessage());
            }
        }
    }

    /**
     * 新手引导 点击事件（下一步、立即体验等）
     *
     * @param view
     */
    public void clickKnown(View view) {
        GuideUtils.onGuideClick(view);
    }

    /**
     * U粉通接口 使用json请求数据（返回结果没有加密）
     *
     * @param requestCode
     * @param params2
     * @param showProgress
     */
    public void sendRequestJson(final int requestCode, String command,
                                JSONObject params2, final boolean showProgress, String url) {
        if (!AppUtil.isNetworkAvailable(this)) {
            AppToast.getToast().show("网络错误!");
            BaseActivity.this.onFailure(requestCode, "网络错误!");
            return;
        }
        if (showProgress) {
            showProgressDialog();
        }
        XRequestCallBack<String> callBack = callBackMap.get(requestCode + "");
        if (callBack == null) {
            callBack = new XRequestCallBack<String>(requestCode) {
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    LogUtil.d("联网失败:" + ex.getMessage());
                    BaseActivity.this.onFailure(getRequestCode(), null);
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    LogUtil.d("联网返回成功:" + result);
                    if (showProgress) {
                        cancelProgressDialog();
                    }

                    try {
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        StringResultBean resultBean = JSON.parseObject(result,
                                StringResultBean.class);
                        if (resultBean.getErrorcode().equals("0")) {
                            LogUtil.e("success>>>>>>");
                            BaseActivity.this.onSuccess(getRequestCode(), resultBean,
                                    result);
                        } else if (resultBean.getErrorcode().equals("110003")) {
                            MySharedPreferences.getInstance().setAuthToken("");
                            MySharedPreferences.getInstance().setLoginStatus(false);
                            BaseActivity.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        } else {
                            LogUtil.e("fail>>>>>>");
                            BaseActivity.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        LogUtil.d("BaseActivity >>  result 数据异常。。");
                        StringResultBean bean = null;
                        BaseActivity.this.onSuccess(getRequestCode(), bean,
                                result);
                    }
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                    this.onFinished();

                }
            };
            callBackMap.put(requestCode + "", callBack);
        }


        RequestParams params = new RequestParams(url);
        //打印请求
        try {
            JSONObject requstJson = new JSONObject();
            if(requestCode != CommandUtil.GETDIALOG) {
                JSONObject clientInfo = new JSONObject();
                long timestamp = System.currentTimeMillis();


                String token = http.DataUtil.md5.MD5.toMd5(http.DataUtil.md5.MD5.toMd5((UrlDef
                        .stringFromJNI() +
                        timestamp).getBytes()).getBytes());
                clientInfo.put("agentId", App.getChannel());
                clientInfo.put("apn", "WIFI");
                clientInfo.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
                clientInfo.put("model", "android");
                clientInfo.put("platform", "android");
                clientInfo.put("timestamp", timestamp);
                clientInfo.put("token", token);
                clientInfo.put("version", App.getVersionName());
                String branch = MySharedPreferences.getInstance().getBranch();
                String companyid = MySharedPreferences.getInstance().getCompanyid();
                if (TextUtil.isEmpty(branch)) {
                    branch = App.BRANCH;
                    MySharedPreferences.getInstance().setBranch(App.BRANCH);
                }
                if (TextUtil.isEmpty(companyid)) {
                    companyid = App.COMPANYID;
                    MySharedPreferences.getInstance().setCompanyid(App.COMPANYID);
                }
                clientInfo.put("branch", branch);
                clientInfo.put("companyid", companyid);
                requstJson.put("clientInfo", clientInfo);
                requstJson.put("command", command);
                if (params2 == null) params2 = new JSONObject();
                params2.put("sysCode", "HM");
                requstJson.put("data", params2);
                LogUtil.d("联网：加密前请求>" + requstJson.toString());
                String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
                LogUtil.d("联网：加密后请求>" + encrypt);
                params.setBodyContent("body=" + encrypt);
                RequestBody body = params.getRequestBody();
                body.setContentType("application/x-www-form-urlencoded");
                params.setRequestBody(body);
            }else {
                requstJson.put("command",command);
                LogUtil.d("联网：加密前请求>" + requstJson.toString());
                String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
                LogUtil.d("联网：加密后请求>" + encrypt);
                params.setBodyContent("body=" + encrypt);
                RequestBody body = params.getRequestBody();
                body.setContentType("application/x-www-form-urlencoded");
                params.setRequestBody(body);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("加密失败");
        }

        LogUtil.v("联网请求：" + params);
        x.http().post(params, callBack);

    }
}
